import Singleton from "../net/Singleton";
import LogUtil from "../utils/LogUtil";

export default class FrameLoading extends Singleton {

    private content: cc.Node = null;
    /**
     * 分帧加载
     * @param itemPrefab 预制节点
     * @param total 加载的总量
     * @param countPerFrame 每帧加载的数量
     * @param content 容器节点
     * @param this0 当前组件
     */
    public loadByFrames(itemPrefab: cc.Prefab, total: number, countPerFrame: number, content: cc.Node, this0: cc.Component, callback: Function) {
        this.content = content
        let index = 0;
        const load = () => {
            const count = Math.min(total - index, countPerFrame);
            for (let i = 0; i < count; i++) {
                const node = cc.instantiate(itemPrefab);
                node.setParent(content);
                callback && callback(node, index);
                index++;
            }
            if (index < total) {
                this0.scheduleOnce(() => load());
            } else {
                LogUtil.log('分帧加载完成');
            }
        }
        load();
    }

    /**
     * 清除
     */
    protected clear() {
        this.content.destroyAllChildren();
    }

}
